package com.oss.robot.project;

import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.LinkStringFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.junit.Test;

import com.oss.model.Project;
import com.oss.robot.BaseRobot;

/**
 * @author xueqiang.mi
 * @since 2010-7-30
 */
public class JBossRobot extends BaseRobot {

	static public final String URL = "http://www.jboss.org/projects";
	static public final String SOURCE = "JBoss";
	static public final String LICENSE = "LGPL";

	static private final String ignoreList = "ProjectsIndex";
	static private final String shortNameList = "EJB3CacheForumsWikiBlog";

	@Test
	public void retrieveProjects() throws ParserException {
		Parser parser = new Parser(URL);
		NodeList nodeList = parser.extractAllNodesThatMatch(new AndFilter(
				new TagNameFilter("li"), new HasAttributeFilter("id",
						"primary-nav-projects")));

		nodeList = nodeList.extractAllNodesThatMatch(new LinkStringFilter("/"),
				true);
		for (Node node : nodeList.toNodeArray()) {
			LinkTag linkTag = (LinkTag) node;
			String name = linkTag.getFirstChild().getText();
			if (ignoreList.contains(name)) {
				continue;
			}
			if (name.length() < 4 || shortNameList.contains(name)) {
				name = "JBoss " + name;
			}
			String url = linkTag.getLink();
			if (url.contains("hibernate") && !url.contains("www")) {
				name = "Hibernate " + name;
			}
			
			Project prj = new Project(name, LICENSE, SOURCE, url);
			prj.setLabel(name);
			prj.setTag("others");
			prj.setEnabled(true);
			prjService.add(prj);
		}
	}
}
